import { request } from '../../request/index'

Page({
  data: {
    leftMenuList: [],
    rightContent: [],
    currentIndex: 0,
    scrollTop: 0
  },
  Cates: [],
  onLoad: function (options) {
    // 数据缓存
    const Cates = wx.getStorageSync('cates')
    if (!Cates) {
      this.getCate()
    } else {
      // 判断过期时间
      if (Date.now() - Cates.time > 1000 * 60 * 5) {
        this.getCate()
      } else {
        this.Cates = Cates.data
        let leftMenuList = this.Cates.map(item => item.cat_name)
        let rightContent = this.Cates[0].children
        this.setData({
          leftMenuList,
          rightContent
        })
      }
    }
  },
  async getCate() {
    const { data: res } = await request({
      url: '/categories'
    })
    if (res.meta.status !== 200) return
    this.Cates = res.message
    // 本地存储
    wx.setStorageSync('cates', {
      time: Date.now(),
      data: this.Cates
    })
    let leftMenuList = this.Cates.map(item => item.cat_name)
    let rightContent = this.Cates[0].children
    this.setData({
      leftMenuList,
      rightContent
    })
  },
  // 左侧列表点击
  handelItemTap(e) {
    const { index } = e.target.dataset
    let rightContent = this.Cates[index].children
    this.setData({
      currentIndex: index,
      rightContent,
      scrollTop: 0
    })
  }
})